package com.ajavaer.framework.web.shiro;

import com.ajavaer.framework.common.tools.JsonTools;
import com.ajavaer.framework.orm.dao.UserFrontDAO;
import com.ajavaer.framework.orm.po.UserAdmin;
import com.ajavaer.framework.orm.po.UserFront;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component("FrontRealm")
public class FrontShiroRealm extends AuthorizingRealm {

    @Resource
    UserFrontDAO userFrontDAO;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Object object = principals.getPrimaryPrincipal();
        UserFront loginUser;
        //注意,redis方式时序列化工具会和devtools冲突,需要使用json转一下才可以
        if (object instanceof UserFront) {
            loginUser = (UserFront) principals.getPrimaryPrincipal();
        } else if (object instanceof UserAdmin) {
            return authorizationInfo;
        } else {
            loginUser = JsonTools.jsonToBean(JsonTools.beanToJson(principals.getPrimaryPrincipal()), UserFront.class);
        }
        loginUser = userFrontDAO.getById(loginUser.getId());
        authorizationInfo.addStringPermission("front:info");
        authorizationInfo.addStringPermission("front:edit");
        authorizationInfo.addStringPermission("front:delete");
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String account = (String) token.getPrincipal();
        UserFront userFront = userFrontDAO.findFirstByAccount(account);
        if (userFront == null) {
            return null;
        }
        userFront.setUserType("UserFront");
        SecurityUtils.getSubject().getSession().setTimeout(30 * 24 * 3600 * 1000L);

        return new SimpleAuthenticationInfo(userFront, userFront.getPassword(), this.getName());
    }

    public void refresh() {
        clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

}
